package edu.hzit.data.controller;

import com.jcraft.jsch.SftpException;
import edu.hzit.data.utils.Sftp;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@RestController
@RequestMapping("video")
public class VideoController {

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

        // 如果文件不为空
        if (!file.isEmpty()) {
            // 获取当前项目根地址
            String contextPaht = request.getContextPath();
            // 获取根地址下面的路径
            String servletPath = request.getContextPath();
            String scherm = request.getScheme();
            // 存放文件路径
            String storePath = "/usr/local/nginx/html/video";
            // 获取上传时的文件名
            String fileName = file.getOriginalFilename();
            // 新建一个file
            File filepath = new File(storePath, fileName);
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs(); // 如果目录不存在就新建目录
            }
            try {
                // 把文件写入目标文件地址
                file.transferTo(new File(storePath + File.separator + fileName));
            } catch (Exception e) {
                e.printStackTrace();
                return "error";
            }
            return "success"; // 成功
        } else {
            return "error";// 失败
        }
    }
    // 获取特定目录下所有文件在界面中展示文件列表
    @RequestMapping("loadFiles")
    public List<String> loadFiles() {
        // File主要作用是用来关联文件
        File file = new File("/usr/local/nginx/html/video/");
        List<String> list = new ArrayList<>();
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) {
                Arrays.sort(files, Comparator.comparing(File::getName));
                for (File f : files) {
                    list.add(f.getName());
                }
            }
        }
        System.out.println(list);
        return list;
    }

    // 下载文件
    @RequestMapping("/download")
    public void downLoad(String filename, HttpServletResponse response) throws Exception {
        String filePath = "/usr/local/nginx/html/video";
        File file = new File(filePath + "/" + filename);
        // 判断目标目录是否存在
        if (file.exists()) {
            // 设置强制下载格式且不打开同事设置编码
            response.setContentType("application/force-download;charset=UTF-8");
            // 设置头信息及编码
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + java.net.URLEncoder.encode(filename, "UTF-8"));
            byte[] buffer = new byte[1024];
            // 文件输入流
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            // 输出流
            OutputStream os = null;
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                // 边读编写，止到读完为止
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                // 关闭流
                if (bis != null) {
                    bis.close();
                }
                if (fis != null) {
                    fis.close();
                }
            }
            // 返回成功状态码
            response.setStatus(HttpServletResponse.SC_OK);
        }else {
            // 如果文件不存在，返回404错误状态码
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }

    }
}
